package cn.fayang.ymcc.service.impl;

import cn.fayang.ymcc.constant.util.AssertUtil;
import cn.fayang.ymcc.domain.Course;
import cn.fayang.ymcc.domain.CourseMarket;
import cn.fayang.ymcc.domain.CourseOrder;
import cn.fayang.ymcc.domain.CourseOrderItem;
import cn.fayang.ymcc.dto.CourseOrderCreateParamsDto;
import cn.fayang.ymcc.dto.PayDto;
import cn.fayang.ymcc.exception.GlobalException;
import cn.fayang.ymcc.feign.CourseUserLearnFeignClient;
import cn.fayang.ymcc.mapper.CourseOrderMapper;
import cn.fayang.ymcc.result.JSONResult;
import cn.fayang.ymcc.service.ICourseOrderItemService;
import cn.fayang.ymcc.service.ICourseOrderService;
import cn.fayang.ymcc.util.CodeGenerateUtils;
import cn.fayang.ymcc.vo.CourseItemVo;
import cn.fayang.ymcc.vo.CourserOrderVo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.rocketmq.client.producer.LocalTransactionState;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author laoxiao
 * @since 2022-07-29
 */
@Service
@Slf4j
public class CourseOrderServiceImpl extends ServiceImpl<CourseOrderMapper, CourseOrder> implements ICourseOrderService {
    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;

    @Autowired
    private CourseUserLearnFeignClient courseInfoForOrderFeignClient;
    @Autowired
    private ICourseOrderItemService courseOrderItemService;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    /**
     * 下单保存数据
     * @param dto
     */
    @Override
    @Transactional
    public String placeOrder(CourseOrderCreateParamsDto dto) {
        //登录人id  暂时写死
        Long loginId = 1L;
        //将传回的ids分割成字符串
        String courseIdsStr = StringUtils.join(dto.getCourseIds(), ",");
        //redis的key
        String key = courseIdsStr+":"+loginId;
        //判断订单是否在有效时间内
        Object token = redisTemplate.opsForValue().get(key);
        AssertUtil.isNotNull(token,"订单已经失效,请重新下单");
        //判断传回的token是否与redis相等
        AssertUtil.isEquals(dto.getToken(),token.toString(),"订单错误，请重新下单");
        JSONResult jsonResult = courseInfoForOrderFeignClient.courseOrderInfo(courseIdsStr);
        //判断是否成功获取到相应的课程信息
        AssertUtil.isTrue(jsonResult.isSuccess(),"信息错误，下单失败！");
        AssertUtil.isNotNull(jsonResult.getData(),"服务不可达，下单失败！");
        //将feign接口返回的数据转换成json格式数据
        String objStr = JSON.toJSONString(jsonResult.getData());
        // 再讲JSON字符串转换为对象
        CourserOrderVo orderVo = JSONObject.parseObject(objStr,CourserOrderVo.class);
        //获取课程与课程销售相关数据
        List<CourseItemVo> courseInfos = orderVo.getCourseInfos();
        AssertUtil.isNotNull(courseInfos,"课程信息有误，下单失败");
        //保存主订单相关数据
        Date date = new Date();
        //CourseOrder order = saveOrder(dto, loginId, date);
        CourseOrder order = new CourseOrder();
        order.setCreateTime(date);
        order.setOrderNo(CodeGenerateUtils.generateOrderSn(loginId));
        order.setStatusOrder(0);
        order.setUserId(loginId);
        order.setVersion(0);
        order.setPayType(dto.getPayType());
        //insert(order);

        StringBuilder sb = new StringBuilder();
        sb.append("课程【");
        // 保存子订单相关数据
        /*saveOrderItem(courseInfos, date, order, sb);*/
        courseInfos.forEach(courseInfoVo->{
            Course course = courseInfoVo.getCourse();
            //获取销售相关数据
            CourseMarket courseMarket = courseInfoVo.getCourseMarket();
            CourseOrderItem item = new CourseOrderItem();
            item.setOrderId(order.getId());
            item.setAmount(courseMarket.getPrice());
            item.setCount(1);
            order.setTotalCount(order.getTotalCount() + 1);
            order.setTotalAmount(order.getTotalAmount().add(item.getAmount()));
            sb.append(course.getName()).append(",");
            item.setCreateTime(date);
            item.setCourseId(course.getId());
            item.setCourseName(course.getName());
            item.setCoursePic(course.getPic());
            item.setVersion(order.getVersion());
            item.setOrderNo(order.getOrderNo());
            //courseOrderItemService.insert(item);
        });

        sb.append("】订单");
        //4.3 修改主订单
        order.setTitle(sb.toString());
       // updateById(order);
        HashMap<Object, Object> map = new HashMap<>();
        map.put("userId",loginId);
        map.put("courseId",courseIdsStr);
        PayDto payDto = new PayDto(
                order.getTotalAmount(),
                order.getPayType(),
                null,
                order.getOrderNo(),
                order.getUserId(),
                JSON.toJSONString(map),
                order.getTitle()
        );


        Message<String> message = MessageBuilder.withPayload(JSON.toJSONString(payDto)).build();
        TransactionSendResult transactionSendResult = rocketMQTemplate.sendMessageInTransaction(
                "service-order-producer",//要和监听器上注解申明的名字一致
                "course-order-topic:course-order-tag",
                message,  //消息体
                order   //额外参数
        );
        log.info("发送完事务消息--检查事务消息状态");
        LocalTransactionState localTransactionState = transactionSendResult.getLocalTransactionState();
        SendStatus sendStatus = transactionSendResult.getSendStatus();
        if(localTransactionState != LocalTransactionState.COMMIT_MESSAGE || sendStatus != SendStatus.SEND_OK ){
            log.info("校验发送事务消息状态异常");
            throw new GlobalException("下单失败！！");
        }
        //发布延时消息
        try {
            SendResult sendResult = rocketMQTemplate.syncSend(
                    "paytimeout-topic:paytimeout-tag",//topic:tag
                    MessageBuilder.withPayload(order.getOrderNo()).build(),//消息体
                    2000,//发送延迟消息的超时时间
                    4//延迟等级  如果是30分钟 16
            );
            SendStatus sendStatus1 = sendResult.getSendStatus();
            if(sendStatus1 != SendStatus.SEND_OK){
                 /*
                   先尝试重试3次，如果3次重试都发不出去
                     1.记录一个log表
                     2.发站内信，发短信，发邮件通知运维人员，人工接入操作
             */
            }
        } catch (Exception e) {
            e.printStackTrace();
            //报错，我们需要做补偿机制
            /*
             先尝试重试3次，如果3次重试都发不出去
             1.记录一个log表
             2.发站内信，发短信，发邮件通知运维人员，人工接入操作
             */
        }


        //5.删除防重复token
        redisTemplate.delete(key);
        return order.getOrderNo();


    }

    /**
     * 保存主,子订单
     * @param courseOrder
     */
    @Override
    public void saveOrderAndItems(CourseOrder courseOrder) {
        CourseOrder orderTmp = selectOrderByOrderNo(courseOrder.getOrderNo());
        AssertUtil.isNull(orderTmp,"订单已经存在，下单失败");
        //保存订单
        insert(courseOrder);//保存主订单
        courseOrder.getItems().forEach(item->{
            item.setOrderId(courseOrder.getId());
            courseOrderItemService.insert(item);//保存子订单
        });
    }

    /**
     * 通过订单唯一标识查询订单
     * @param orderNo
     * @return
     */
    @Override
    public CourseOrder selectOrderByOrderNo(String orderNo) {
        Wrapper<CourseOrder> wrapper = new EntityWrapper<>();
        wrapper.eq("order_no",orderNo);
        return selectOne(wrapper);
    }
    /**
     * 修改订单状态
     */
    @Override
    public void payOrder(CourseOrder courseOrder) {
        courseOrder.setStatusOrder(CourseOrder.STATE_PAY_SUCCESS);
        courseOrder.setUpdateTime(new Date());
        updateById(courseOrder);

    }

    /**
     * 订单支付超时取消
     * @param orderNo
     */
    @Override
    public void cancelOrder(String orderNo) {
        //应该拿着订单号去支付宝查询一波，看订单是否支付成功  不调用了
        CourseOrder courseOrder = selectOrderByOrderNo(orderNo);
        AssertUtil.isNotNull(courseOrder,"订单不存在");
        if(courseOrder.getStatusOrder().intValue() != CourseOrder.STATE_PAY_SUCCESS.intValue()){
            courseOrder.setStatusOrder(CourseOrder.STATE_CANCEL);
            updateById(courseOrder);
        }
    }

    /* *//**
     * 保存子订单相关数据
     * @param courseInfos
     * @param date
     * @param order
     * @param sb
     *//*
    private void saveOrderItem(List<CourseItemVo> courseInfos, Date date, CourseOrder order, StringBuilder sb) {
        courseInfos.forEach(courseInfoVo->{
            Course course = courseInfoVo.getCourse();
            //获取销售相关数据
            CourseMarket courseMarket = courseInfoVo.getCourseMarket();
            CourseOrderItem item = new CourseOrderItem();
            item.setOrderId(order.getId());
            item.setAmount(courseMarket.getPrice());
            item.setCount(1);
            order.setTotalCount(order.getTotalCount() + 1);
            order.setTotalAmount(order.getTotalAmount().add(item.getAmount()));
            sb.append(course.getName()).append(",");
            item.setCreateTime(date);
            item.setCourseId(course.getId());
            item.setCourseName(course.getName());
            item.setCoursePic(course.getPic());
            item.setVersion(order.getVersion());
            item.setOrderNo(order.getOrderNo());
            courseOrderItemService.insert(item);
        });
    }

    *//**
     * 保存主订单相关数据
     * @param dto
     * @param loginId
     * @param date
     * @return
     *//*
    private CourseOrder saveOrder(CourseOrderCreateParamsDto dto, Long loginId, Date date) {
        CourseOrder order = new CourseOrder();
        order.setCreateTime(date);
        order.setOrderNo(CodeGenerateUtils.generateOrderSn(loginId));
        order.setStatusOrder(0);
        order.setUserId(loginId);
        order.setVersion(0);
        order.setPayType(dto.getPayType());
        insert(order);
        return order;
    }*/
}
